<template>
  <div>
    <commonBox one="商品管理" tow="商品列表"></commonBox>
    <!-- 卡便 -->
    <el-card>
      <el-alert
        title="添加商品！"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeindex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息">基本信息</el-step>
        <el-step title="商品参数">商品参数</el-step>
        <el-step title="商品属性">商品属性</el-step>
        <el-step title="商品图片">商品图片</el-step>
        <el-step title="商品内容">商品内容</el-step>
        <el-step title="完成 ">完成</el-step>
      </el-steps>

      <!-- 表单包裹左侧导航 -->
      <el-form
        :model="shopruleForm"
        :rules="shoprules"
        ref="shopref"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <!-- 左侧导航 -->
        <el-tabs
          v-model="activeindex"
          @tab-click="handleClick"
          tab-position="left"
          :before-leave="brforeleave"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 基本信息 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="shopruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="shopruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="shopruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="shopruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品内容" prop="goods_cat">
              <el-cascader
                clearable
                v-model="shopruleForm.goods_cat"
                :options="listdata"
                :props="shopprops"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 商品参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manydata"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item2"
                  v-for="(item2, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 商品属性 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in olnydata"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 商品图片 -->
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handlesuccsee"
              :headers="heade"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 商品内容 -->
            <quill-editor v-model="shopruleForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btn" @click="addsub"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 弹框 -->
    <el-dialog title="预览图片" :visible.sync="adddialogVisible" width="50%">
      <img :src="datasrc" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      // 预览图片路径
      datasrc: "",
      // 预览图片boolear
      adddialogVisible: false,
      // 获取列表数据
      listdata: [],
      // 步骤条
      activeindex: "0",
      //   表单数据请求信息
      shopruleForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: [],
      },
      //   表单验证规则
      shoprules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
      },
      //   级联选择器配置对象
      shopprops: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
        checkStrictly: true,
      },
      manydata: [],
      olnydata: [],
      heade: {
        Authorization: window.sessionStorage.getItem("token"),
      },
    };
  },
  created() {
    this.getlistdata();
  },
  methods: {
    async getlistdata() {
      const { data: res } = await this.$http.get("categories");
      console.log(res);

      this.listdata = res.data;
    },
    // 级联选择发生改变触发
    handleChange() {
      if (this.shopruleForm.goods_cat.length !== 3) {
        this.shopruleForm.goods_cat = [];
        return null;
      }
    },
    // 左侧导航点击事件
    async handleClick() {
      //   console.log(this.activeindex);
      if (this.activeindex == 1) {
        const { data: res } = await this.$http.get(
          `categories/${this.attr_id}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        console.log(res);
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(",");
        });
        this.manydata = res.data;
        console.log(this.manydata);
      }
      if (this.activeindex == 2) {
        const { data: res } = await this.$http.get(
          `categories/${this.attr_id}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        console.log(res);
        this.olnydata = res.data;
      }
    },
    // 阻止条状
    brforeleave(activeName, oldActiveName) {
      if (this.activeindex == "0" && this.shopruleForm.goods_cat.length !== 3) {
        this.$message.error("先选择分类");
        return false;
      }
    },
    // 预览
    handlePreview(file) {
      console.log(file, "...");
      this.datasrc = file.response.data.url;
      this.adddialogVisible = true;
    },
    // 移除
    handleRemove(file) {
      console.log(file.response.data.tmp_path);
      const imgpath = file.response.data.tmp_path;
      const i = this.shopruleForm.pics.findIndex((item) => {
        item.pic == imgpath;
      });
      console.log(i);
      this.shopruleForm.pics.splice(i, 1);
      console.log(this.shopruleForm.pics);
    },
    // 上传成功响应
    handlesuccsee(response) {
      // console.log(response);
      const addimg = response.data.tmp_path;
      const ingpath = { pic: addimg };
      this.shopruleForm.pics.push(ingpath);
      console.log(this.shopruleForm.pics);
    },
    // 确定增加按钮
    addsub() {
      this.$refs.shopref.validate(async (valid) => {
        if (!valid) {
          return this.$message.error("填写");
        }

        // 先深拷贝shopprops数据
        const from = _.cloneDeep(this.shopruleForm);
        from.goods_cat = from.goods_cat.join(",");
        // console.log(from);
        // 处理attrs？数据

        // 处理动态参数数据
        this.manydata.forEach((item) => {
          const newinfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.shopruleForm.attrs.push(newinfo);
        });
        //  静态属性
        this.olnydata.forEach((item) => {
          const newinfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          // console.log(newinfo);
          this.shopruleForm.attrs.push(newinfo);
        });
        from.attrs = this.shopruleForm.attrs;
        console.log(from);
        const { data: res } = await this.$http.post("goods", from);
        console.log(res);
        this.$router.push("/goods");
      });
    },
  },
  computed: {
    attr_id() {
      if (this.shopruleForm.goods_cat.length !== 3) {
        return null;
      }
      return this.shopruleForm.goods_cat[2];
    },
  },
};
</script>
<style lang="less" scoped>
img {
  width: 100%;
}

.btn {
  margin-top: 80px;
}
</style>